import React, { useEffect, useState } from 'react';
import { NavBar, List, Image, Tag, Tabs, Empty, Card, Rate, Toast } from 'react-vant';
import { useNavigate, useSearchParams } from 'react-router-dom';
import axios from '../../request/axios';
import './list.less';

interface Doctor {
  doctorId: number;
  doctorName: string;
  imagePic: string;
  jobTitle: string;
  inauguralHospital: string;
  praise: number;
  serverNum: number;
  servicePrice: number;
  praiseNum: number;
  badNum: number;
}

interface ApiResponse {
  status: string;
  message: string;
  result: Doctor[];
}

const sortOptions = [
  { text: '综合排序', value: 1 },
  { text: '好评优先', value: 2 },
  { text: '咨询量优先', value: 3 },
  { text: '价格排序', value: 4 },
];

const DoctorList: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [loading, setLoading] = useState(false);
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [finished, setFinished] = useState(false);
  const [page, setPage] = useState(1);
  const [condition, setCondition] = useState(1);
  const [sortBy, setSortBy] = useState<number | undefined>();
  const deptId = searchParams.get('deptId') || '1'; // 默认科室ID为1

  const fetchDoctors = async (pageNum: number = 1, isRefresh: boolean = false) => {
    try {
      setLoading(true);
      const response = await axios.get<ApiResponse>(
        '/health/user/inquiry/v1/findDoctorList',
        {
          params: {
            deptId: 2,
            condition:1,
            page: 1,
            count: 10,
            sortBy: 1,
          }
        }
      );
      console.log(response);
      
      if (response.data.status === '0000') {
        const newList = response.data.result || [];
        if (isRefresh) {
          setDoctors(newList);
        } else {
          setDoctors(prev => [...prev, ...newList]);
        }
        setFinished(newList.length < 10);
      } else {
        console.error('获取医生列表失败:', response.data.message);
      }
    } catch (error) {
      console.error('请求失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setPage(1);
    fetchDoctors(1, true);
  }, [deptId, condition, sortBy]);

  const onRefresh = async () => {
    setPage(1);
    await fetchDoctors(1, true);
  };

  const onLoad = async () => {
    if (!finished) {
      const nextPage = page + 1;
      setPage(nextPage);
      await fetchDoctors(nextPage);
    }
  };

  const handleSortChange = (value: number) => {
    setCondition(value);
    if (value === 4) {
      setSortBy(1); // 默认高价格排序
    } else {
      setSortBy(undefined);
    }
  };

  const handleDoctorClick = (doctorId: number) => {

    navigate(`/doctor/detail/${doctorId}`);
  };

  return (
    <div className="doctor-list-page">
      <NavBar
        title="找医生"
        leftText="返回"
        onClickLeft={() => navigate(-1)}
      />

      <Tabs 
        value={condition}
        onChange={handleSortChange}
        sticky
        className="sort-tabs"
      >
        {sortOptions.map(option => (
          <Tabs.TabPane 
            key={option.value} 
            title={option.text}
            name={option.value}
          />
        ))}
      </Tabs>

      <List
        className="doctor-list"
        loading={loading}
        finished={finished}
        onLoad={onLoad}
        offset={10}
        finishedText="没有更多了"
      >
        {doctors.length === 0 && !loading ? (
          <Empty description="暂无医生" />
        ) : (
          doctors.map((doctor) => (
            <Card
              key={doctor.doctorId}
              onClick={() => handleDoctorClick(doctor.doctorId)}
              className="doctor-card"
            >
              <div className="doctor-info">
                <Image
                  className="avatar"
                  src={doctor.imagePic || '/default-doctor.png'}
                  fit="cover"
                />
                <div className="info-content">
                  <div className="name-title">
                    <span className="name">{doctor.doctorName}</span>
                    <Tag type="primary" className="title">{doctor.jobTitle}</Tag>
                  </div>
                  <div className="hospital">{doctor.inauguralHospital}</div>
                  <div className="stats">
                    <Rate 
                      value={doctor.praise * 5} 
                      count={5} 
                      readonly 
                      size={12}
                    />
                    <span className="rate">{(doctor.praise * 100).toFixed(1)}%好评</span>
                    <span className="separator">|</span>
                    <span className="patients">问诊{doctor.serverNum}人</span>
                  </div>
                </div>
                <div className="price">
                  <span className="amount">￥{doctor.servicePrice}</span>
                  <span className="unit">/次</span>
                </div>
              </div>
            </Card>
          ))
        )}
      </List>
    </div>
  );
};

export default DoctorList; 